package com.android.common.filetools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.util.Log;

public class FileUtils {  
	
	private int FILESIZE = 8 * 1024;

	private FileOutputStream fos; 
	
	 
	
	public FileUtils(){
		 
	}
	
	/**
	 * 在SD卡上创建文件
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public File createSDFile(String dirfileName) throws IOException{
		Log.d("dirfileName<<", ""+dirfileName);
		File file = new File(dirfileName);
		file.createNewFile();
		return file;
	}
	
	/**
	 * 在SD卡上创建目录
	 * @param dirName
	 * @return
	 */
	public File createSDDir(String dirName){
		Log.d("dirName<<", ""+dirName);
		File dir = new File(dirName);
		dir.mkdirs();
		return dir;
	}
	
	/**
	 * 判断SD卡上的文件夹是否存在
	 * @param fileName
	 * @return
	 */
	public boolean isFileDirExist(String filepath){
		
		File file = new File(filepath);
		return file.exists();
	}
	/**
	 * 判断SD卡上的文件是否存在
	 * @param fileName
	 * @return
	 */
	public boolean isFileExist(String filepath,String fileName){
		File file = new File( filepath+"/"+fileName);
		return file.exists();
	}
	
	/**
	 * 删除指定文件
	 * @param strFileName  文件路径加名字
	 * @return
	 */
	public static void delFile(String strFileName) {
		File myFile = new File(strFileName);
		if (myFile.exists()) {
			myFile.delete();
		}
	}
	
	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 * @param path
	 * @param fileName
	 * @param input
	 * @return
	 */
	public File write2SDFromInput(String path,String fileName,InputStream input){
		File file = null;
		 
		try {
			createSDDir(path);  
			file = createSDFile(path +"/"+ fileName);
			if (file.exists()) { 
				fos = new FileOutputStream(path + "/"+fileName);
				byte[] buffer = new byte[FILESIZE];
				int count = 0;
				// 开始复制文件
				while ((count = input.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				} 
				fos.flush(); 
			} 
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		 
		return file;
	}

}
